﻿using System.Linq;

namespace Borg.Framework
{
    public class ReplaceRegister
    {
        internal bool global;
        public SlotInfo slot;

        public ReplaceRegister(SlotInfo slot)
        {
            this.slot = slot;
            slot.Registering += Registering;
        }

        public ReplaceRegister(SlotInfo slot, bool global)
            : this(slot)
        {
            this.global = global;
        }

        private void Registering(object sender, CancelRegisterEventArgs args)
        {
            if (global)
            {
                var si = Runtime.Repository.SlotInfos.Find(slot.Name);

                foreach (var slotInfo in si)
                    foreach (var pti in slotInfo.RegisteredPlugTypeInfos.
                        Where(pti => pti != args.PlugTypeInfo))
                        slotInfo.Deregister(pti);

                args.PlugTypeInfo.Register();
            }
            else
            {
                foreach (var pti in slot.RegisteredPlugTypeInfos.
                    Where(pti => pti != args.PlugTypeInfo))
                    slot.Deregister(pti);
            }
        }
    }
}

